import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import threading
from converter import DocConverter

class DocConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("DOC转训练数据集工具")
        self.root.geometry("800x600")
        
        # 初始化变量
        self.input_folder = tk.StringVar()
        self.output_folder = tk.StringVar()
        
        # 创建转换器实例
        self.converter = DocConverter(log_callback=self.log_message)
        
        self.setup_ui()
        
    def setup_ui(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 输入文件夹选择
        input_frame = ttk.LabelFrame(main_frame, text="输入文件夹", padding="5")
        input_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
        
        ttk.Entry(input_frame, textvariable=self.input_folder, width=50).grid(row=0, column=0, padx=5)
        ttk.Button(input_frame, text="浏览...", command=self.select_input_folder).grid(row=0, column=1, padx=5)
        
        # 输出文件夹选择
        output_frame = ttk.LabelFrame(main_frame, text="输出文件夹", padding="5")
        output_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
        
        ttk.Entry(output_frame, textvariable=self.output_folder, width=50).grid(row=0, column=0, padx=5)
        ttk.Button(output_frame, text="浏览...", command=self.select_output_folder).grid(row=0, column=1, padx=5)
        
        # 选项框架
        options_frame = ttk.LabelFrame(main_frame, text="转换选项", padding="5")
        options_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
        
        # 输出格式选择
        ttk.Label(options_frame, text="输出格式:").grid(row=0, column=0, sticky=tk.W, padx=5)
        self.format_var = tk.StringVar(value="jsonl")
        format_combo = ttk.Combobox(options_frame, textvariable=self.format_var, state="readonly", width=15)
        format_combo['values'] = ('jsonl', 'txt')
        format_combo.grid(row=0, column=1, sticky=tk.W, padx=5)
        
        # 数据处理选项
        self.remove_empty_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(options_frame, text="移除空行", variable=self.remove_empty_var).grid(row=1, column=0, sticky=tk.W, padx=5)
        
        self.min_length_var = tk.IntVar(value=5)
        ttk.Label(options_frame, text="最小段落长度:").grid(row=1, column=1, sticky=tk.W, padx=5)
        ttk.Spinbox(options_frame, from_=1, to=100, textvariable=self.min_length_var, width=5).grid(row=1, column=2, sticky=tk.W, padx=5)
        
        # 转换按钮
        self.convert_btn = ttk.Button(main_frame, text="开始转换", command=self.start_conversion)
        self.convert_btn.grid(row=3, column=0, pady=10)
        
        # 停止按钮
        self.stop_btn = ttk.Button(main_frame, text="停止转换", command=self.stop_conversion, state=tk.DISABLED)
        self.stop_btn.grid(row=3, column=1, pady=10)
        
        # 进度条
        self.progress = ttk.Progressbar(main_frame, mode='indeterminate')
        self.progress.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
        
        # 日志框
        log_frame = ttk.LabelFrame(main_frame, text="日志", padding="5")
        log_frame.grid(row=5, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(log_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.log_text = tk.Text(log_frame, height=15, yscrollcommand=scrollbar.set)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.log_text.yview)
        
        # 配置权重使界面可调整大小
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(5, weight=1)
        
    def select_input_folder(self):
        folder = filedialog.askdirectory(title="选择包含DOC/DOCX文件的文件夹")
        if folder:
            self.input_folder.set(folder)
            
    def select_output_folder(self):
        folder = filedialog.askdirectory(title="选择输出文件夹")
        if folder:
            self.output_folder.set(folder)
            
    def log_message(self, message):
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.root.update_idletasks()
        
    def start_conversion(self):
        if not self.input_folder.get() or not self.output_folder.get():
            messagebox.showerror("错误", "请选择输入和输出文件夹")
            return
            
        if self.converter.is_converting:
            return
            
        self.convert_btn.config(state=tk.DISABLED)
        self.stop_btn.config(state=tk.NORMAL)
        self.progress.start()
        
        # 在后台线程中运行转换
        thread = threading.Thread(target=self.run_conversion)
        thread.daemon = True
        thread.start()
        
    def run_conversion(self):
        input_dir = self.input_folder.get()
        output_dir = self.output_folder.get()
        output_format = self.format_var.get()
        min_length = self.min_length_var.get()
        remove_empty = self.remove_empty_var.get()
        
        success, message = self.converter.convert_documents(
            input_dir, output_dir, output_format, min_length, remove_empty
        )
        
        self.conversion_complete(success, message)
        
    def stop_conversion(self):
        self.converter.stop_conversion()
        
    def conversion_complete(self, success, message):
        """转换完成后的清理工作"""
        self.progress.stop()
        self.convert_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        
        if success:
            messagebox.showinfo("完成", message)
        else:
            messagebox.showerror("错误", message)
